<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px; margin-bottom: 20px" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加图片
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="序号" prop="id" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="内容" prop="content" align="center">
        <template slot-scope="{ row }">
          <span class="item-content">{{ row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="image" align="center">
        <template slot-scope="{ row }">
          <img :src="row.image" alt="" width="160" height="80">
        </template>
      </el-table-column>

      <el-table-column label="排序" prop="sort" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>

      <el-table-column label="展示位" prop="type" align="center">
        <template slot-scope="{ row }">

          <span>{{ row.type_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" prop="updateTime" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.update_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.create_time }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px">
        <el-form-item>
          <el-upload action="admin/upload/image" :show-file-list="false" :on-success="handleUploadSuccess" :accept="'image/*'">
            <img width="100%" :src="'http://mmall.alliky.com'+temp.image" alt="">
            <el-button class="filter-item" type="primary" size="medium">
              上传图片
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="标题">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="跳转链接">
          <el-input v-model="temp.link" />
        </el-form-item>
        <el-form-item label="广告类型">
          <el-select v-model="temp.type_name" value-key="temp.type" placeholder="请选择" @change="handleSelect">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.type_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="temp.content" :autosize="{ minRows: 1, maxRows: 4 }" type="textarea" placeholder="内容" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" :autosize="{ minRows: 1, maxRows: 4 }" type="textarea" placeholder="描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchType,
  createBanner,
  deleteBanner
} from '@/api/banner'
import {
  parseTime
} from '@/utils'

export default {
  name: 'Index',
  components: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      listLoading: true,
      downloadLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      options: null,
      type_id: 0,
      temp: {
        id: undefined,
        content: '',
        title: '',
        sort: 1,
        type: 1,
        status: 1,
        link: '',
        image: '',
        type_name: ''
      },
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        startTime: [{
          type: 'date',
          required: true,
          message: 'startTime is required',
          trigger: 'change'
        }],
        endTime: [{
          type: 'date',
          required: true,
          message: 'endTime is required',
          trigger: 'change'
        }],
        image: [{
          required: true,
          message: 'imgUrl is required',
          trigger: 'blur'
        }],
        title: [{
          required: true,
          message: 'title is required',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.getList()
    this.getTypeList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList().then((response) => {
        this.list = response.data.list
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      })
    },

    getTypeList() {
      fetchType().then((response) => {
        this.options = response.data.list
      })
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response)
      this.temp.image = response.data.image
    },

    handleSelect(val) {
      var obj = this.options
      var hostValue = {}
      obj.forEach((item, index) => {
        const id = item.id
        if (!hostValue[id]) {
          hostValue[id] = {
            item
          }
        }
      })
      this.temp.type = hostValue[val].item.id
      console.log(this.temp.type)
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createBanner(this.temp).then((response) => {
            if (response.code === 0) {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: response.message
              })
            }
          })
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp.id = row.id
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.createData()
        }
      })
    },

    deleteData(param) {
      deleteBanner(param).then((response) => {
        if (response.code === 0) {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
      })
    },

    handleDelete(row) {
      const data = {
        id: row.id
      }
      this.$confirm('此操作将会删除这条记录，是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteData(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        content: '',
        sort: 1,
        type: 1,
        status: 1,
        link: '',
        image: '',
        type_name: ''
      }
    }
  }
}
</script>

<style lang="scss">
.item-content {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}
</style>
